< previous page page_204 next page >

Page 204
In Chapter 9, "Visual Basic Programming Fundamentals," you learned how to create a number of programming code statements. Now, you will see how to enhance this knowledge by controlling the order in which parts of your program code are executed.
Two of the fundamental strengths of computers are their capabilities to execute instructions quickly and to make decisions precisely. In this chapter, you will learn how to take advantage of these capabilities in two very important ways: through the use of decision-making techniques and the use of loops, which allow portions of code to run a controlled number of times. Also, you will learn how to make your code react to errors that may occur during program execution.
Making Decisions in Your Program
In Chapter 9, you learned about a class of code statements known as assignment statements, which are used to set and modify the values of variables. Another group of statements is important for handling more complex tasks. These statements are known collectively as control statements. Without control statements, your program would start at the first line of code and proceed line by line until the last line was reached, at which point the program would stop.
One type of control statement is the decision statement. This statement is used to control the execution of parts of your program, based on conditions that exist at the time the statement is encountered. The two basic types of decision statements are If statements and Select Case statements. Each is covered in the following sections.
Using the If Statement
For many decisions, you may want to execute a statement (or group of statements) only if a particular condition is True. Two forms of the If statement handle True conditions: the single-line If statement and the multiple-line If statement. Each uses the If statement to check a condition. If the condition is True, the program runs the commands associated with the If statement. For example, the following two If statements perform the same function:
'Single-Line IF
If x > 5 then x = 0

'Multiple-Line IF
If x > 5 Then
    x = 0
End If
Note that indenting lines of code in a multiple-line If statement is a customary formatting practice. This indentation makes the code more readable when you use nested Ifs.
If the condition is False (in the preceding example, if x is not greater than 5), the commands on the If line (single-line If) or between the If and End If statements (multiple-line If) are skipped, and the next line of code is executed.
The Single-Line If Statement
You use the single-line If statement to perform a single task when the condition in the statement is True. The task can be a single command, or you can

 
< previous page page_204 next page >